@include "misc.awk"
@include "reader.awk"
@include "euclid.awk"

function bore(   _local) { 
    OFS=FS=","; 
    args("in=/dev/stdin;top=25",Opt,_local)
    boreMain(Opt["in"],Opt["top"])
}
function boreMain(f,enough,    r,t,n) {
    lines(f,t)
    for(r=t["rows"];r>=1;r--) scoreRow(t,r)
    report(t, border(t["score"],enough))
}
function scoreRow(t,r,       c,sum,score,util) {  
    util=10^-10
    for(c in t["class"]) 
        if (t[r][c] != "?") {
            sum  += (t["heaven"][c] - norm(t,t[r][c],c))^2
            util += t["weight"][c] }
     t["score"][r] =  1 - (sqrt(sum) / sqrt(util))
}
function border(scores,enough,   sorted,n) {
    n = asort(scores, sorted)    
    return sorted[round(n*(1- enough/100))]
}
function usedRow2String(t,r,score,threshold,_sep,     c,out) {
    _sep = the(_sep,",")
    for(c=1;c<=length(t[r]);c++)  
        if (c in t["use"]) 
            out = out t[r][c] _sep
    return out score _sep (score >= threshold ? "+" : "-")
}
function report(t,s,_sep,      c,r,out) {
    _sep = the(_sep,",")
    for(c=1;c<=t["cols"];c++)
        if(c in t["use"]) 
            out = out noclass(t["string"][c]) _sep
    print out "?$score" _sep "!+-"
    for(r=1;r<=t["rows"];r++)
        print usedRow2String(t,r,t["score"][r],s)
}
function noclass(x) { gsub(/[!<>]/,"",x); return x }
